<script lang="ts" setup>
import { computed, reactive, ref } from "vue";
import api from "@/api";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { MachineTunnelSaveCmd, MachineType } from "@/types";
import { MachineSelect } from "@/components/business";

const emit = defineEmits(["success"]);

interface State {
  visible: boolean;
  form: MachineTunnelSaveCmd;
}

const state = reactive<State>({
  visible: false,
  form: new MachineTunnelSaveCmd()
});

const title = computed(() => {
  return state.form.id ? "编辑隧道" : "新建隧道";
});

const formRef = ref<FormInstance | null>(null);

const rules: FormRules<MachineTunnelSaveCmd> = {
  name: [{ required: true, message: "请输入", trigger: ["blur", "change"] }],
  machineId: [{ required: true, message: "请选择", trigger: ["blur", "change"] }],
  type: [{ required: true, message: "请选择", trigger: ["blur", "change"] }],
  localIp: [
    { required: true, message: "请输入", trigger: ["blur", "change"] },
    {
      pattern:
        /^((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))$/,
      message: "ip格式不正确",
      trigger: ["blur", "change"]
    }
  ],
  localPort: [
    { required: true, message: "请输入", trigger: ["blur", "change"] },
    { pattern: /^[0-9]*$/, message: "请输入数字", trigger: ["blur", "change"] }
  ],
  remotePort: [
    {
      validator: (rule, value, callback) => {
        if (state.form.type === 3) {
          callback();
          return;
        }
        if (!value || value.length == 0) {
          // 自定义验证条件，返回错误提示文字
          callback(new Error("请输入"));
        } else {
          callback();
        }
      },
      trigger: ["blur", "change"]
    },
    { pattern: /^[0-9]*$/, message: "请输入数字", trigger: ["blur", "change"] }
  ],
  remoteIp: [
    {
      validator: (rule, value, callback) => {
        if (state.form.type !== 1) {
          callback();
          return;
        }
        if (!value || value.length == 0) {
          // 自定义验证条件，返回错误提示文字
          callback(new Error("请输入"));
        } else {
          callback();
        }
      },
      trigger: ["blur", "change"]
    },
    {
      pattern:
        /^((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))$/,
      message: "ip格式不正确",
      trigger: ["blur", "change"]
    }
  ]
};

const submit = () => {
  formRef.value?.validate((valid, fields) => {
    if (valid) {
      api.machineTunnel.saveMachineTunnel(state.form).then((r) => {
        emit("success");
        ElMessage.success("保存成功");
        state.visible = false;
      });
    }
  });
};

const reset = () => {
  state.form = new MachineTunnelSaveCmd();
  formRef.value?.resetFields();
};

const openDialog = (id?: string) => {
  state.visible = true;
  if (id) {
    api.machineTunnel.getMachineTunnel(id).then((r) => {
      state.form = {
        id: r.data.id,
        machineId: r.data.machineId,
        name: r.data.name,
        type: r.data.type,
        localPort: r.data.localPort,
        remotePort: r.data.remotePort,
        remoteIp: r.data.remoteIp,
        localIp: r.data.localIp
      };
      //   state.form.machineId = data.data.machine.id;
    });
  }
};

const closeDialog = () => {
  state.visible = false;
};

defineExpose({
  openDialog,
  closeDialog
});
</script>

<template>
  <el-dialog
    v-model="state.visible"
    :title="title"
    :close-on-click-modal="false"
    width="600"
    @open="reset"
    append-to-body
  >
    <div>
      <el-form
        :model="state.form"
        ref="formRef"
        :rules="rules"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="隧道名称" prop="name">
          <el-input v-model="state.form.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="关联主机" prop="machineId">
          <machine-select
            v-model="state.form.machineId"
            :id="state.form.machineId"
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item label="隧道类型" prop="type">
          <el-radio-group v-model="state.form.type">
            <el-radio :value="1">本地转发</el-radio>
            <el-radio :value="2">远程转发</el-radio>
            <el-radio :value="3">动态转发</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="本地IP" prop="localIp">
          <el-input v-model="state.form.localIp" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="本地端口" prop="localPort">
          <el-input v-model="state.form.localPort" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="远程IP" v-show="state.form.type === 1" prop="remoteIp">
          <el-input v-model="state.form.remoteIp" placeholder="请输入" />
        </el-form-item>
        <el-form-item
          label="远程端口"
          prop="remotePort"
          v-show="state.form.type === 1 || state.form.type === 2"
        >
          <el-input v-model="state.form.remotePort" placeholder="请输入" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="state.visible = false">取消</el-button>
        <el-button type="primary" @click="submit"> 确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>
